package com.smartcruise.service;

import com.smartcruise.data.cruiseData.CruiseContract;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.util.Key;
import com.smartcruise.util.TempleUser;
import com.smartcruise.util.TimeUtils;
import com.smartcruise.util.pushUtil.NotificationUtils;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by FengChaoQun
 * on 2018/2/27 0027
 * 后台检查任务数据的线程
 * 1.根据原任务数据 产生今天需要执行的任务
 * 2.检查当前是否需要执行任务，如果需要，弹出提示
 */

public class CruiseThread extends Thread {

    private final int period = 10 * 1000;

    @Override
    public void run() {
        super.run();

        while (true) {
            try {
                Thread.sleep(period);

                try (Realm realm = Realm.getDefaultInstance()) {
                    //先查找出所有的原数据
                    final RealmResults<CruiseData> all = realm.where(CruiseData.class)
                            .equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                            .equalTo(Key.isCopyData, false)
                            .equalTo(Key.isFromNet, false)
                            .findAll();

                    //构造当天需要执行的任务
                    for (CruiseData cruiseData : all) {
                        CruiseContract.buildTodayTask(cruiseData, realm);
                    }

                    checkTask(realm);
                }

                //通知handler
                TimerHandler.getInstance().sendEmptyMessage(TimerHandler.timer);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * description:检查任务 提醒将要执行的任务
     */
    private final static long noticeAdvance = 60 * 60 * 1000;//提前通知的时间

    private void checkTask(Realm realm) {
        //找出未提醒的待执行的所有本地任务
        RealmResults<CruiseData> all = realm.where(CruiseData.class).equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                .equalTo(Key.isCopyData, true)
                .equalTo(Key.statusInApp, CruiseContract.TASK_IS_WAIT_START)
                .equalTo("notice", false)
                .findAll();

        for (final CruiseData cruiseData : all) {
            if (cruiseData.getShouldRunDate() - TimeUtils.currentTime() < noticeAdvance) {
                NotificationUtils.showTaskNotification(cruiseData.getName());
                //通知完成后将本地的任务设置为已通知 防止重复通知
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        cruiseData.setNotice(true);
                    }
                });
            }
        }
    }

}
